package com.yaowk.system.server.controller;

import com.yaowk.common.api.PageReq;
import com.yaowk.common.api.PageResp;
import com.yaowk.common.api.StatusDict;
import com.yaowk.system.api.UserApi;
import com.yaowk.system.api.model.User;
import com.yaowk.system.server.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "用户管理")
public class UserController implements UserApi {

    @Autowired
    private IUserService userService;
    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;

    @Override
    @ApiOperation("查询用户列表")
    public PageResp<User> findAll(User user, PageReq pageReq) {
        if (ObjectUtils.isEmpty(user.getStatus())) {
            user.setStatus(StatusDict.TRUE);
        }
        return userService.findAll(user, pageReq);
    }

    @Override
    @ApiOperation("查询用户详情")
    public User findOne(@PathVariable Long id) {
        return userService.findById(id);
    }

    @Override
    @ApiOperation("保存用户")
    public User save(User user) {
        if (StringUtils.isNotBlank(user.getPassword()) && !ObjectUtils.isEmpty(passwordEncoder)) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return userService.save(user);
    }

    @Override
    @ApiOperation("删除用户")
    public void delete(@PathVariable Long id) {
        userService.deleteById(id);
    }
}
